﻿using GamFi.API.Application.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace GamFi.API.Infrastructure.Services;

public class MessageCleanupHostedService(
    IServiceScopeFactory serviceScopeFactory,
    ILogger<MessageCleanupHostedService> logger)
    : BackgroundService
{
    private readonly TimeSpan _cleanupInterval = TimeSpan.FromMinutes(5);

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = serviceScopeFactory.CreateScope();
                var cleanupService = scope.ServiceProvider.GetRequiredService<ICleanupService>();
                await cleanupService.RemoveOldMessagesAsync(stoppingToken);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error occurred during message cleanup.");
            }

            await Task.Delay(_cleanupInterval, stoppingToken);
        }
    }
}
